# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '677501769574': {  # witch 支付宝 10-3000
        'API_KEY': '471e1a3e1f70254a88f3ec2bc79da734',
        'gateway': 'http://api.baokanju.com.cn:12702/waporder/order_add',
        'query_gateway': 'http://api.baokanju.com.cn:12702/lqpay/showquery',
    },
    '711669096874': {  # loki 支付宝 10-3000
        'API_KEY': 'a23563716d9a5d38eea64917fd102427',
        'gateway': 'http://api.baokanju.com.cn:12702/waporder/order_add',
        'query_gateway': 'http://api.baokanju.com.cn:12702/lqpay/showquery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


# md5(order_id+money+pay_type+time+ mch+md5 (key) )
def generate_sign(d, key):
    s = d['order_id'] + d['money'] + d['pay_type'] + d['time'] + d['mch'] + _gen_sign(key)
    _LOGGER.info("shenglipay_v2 sign str: %s", s)
    return _gen_sign(s)


# (订单号码+系统订单+支付金额+商务号+支付类型+时间戳.md5(商户密钥))
def generate_notify_sign(d, key):
    s = d['order_id'] + str(d['orderNo']) + str(d['money']) + d['mch'] + d['pay_type'] + str(d['time']) + _gen_sign(key)
    _LOGGER.info("shenglipay_v2 sign str: %s", s)
    return _gen_sign(s)


# md5(mch+order_id+money+pay_type+time+md5(key))
def generate_query_sign(d, key):
    s = d['mch'] + d['order_id'] + d['money'] + d['pay_type'] + d['time'] + _gen_sign(key)
    _LOGGER.info("shenglipay_v2 sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("shenglipay_v2 sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay':
        return 'aliwap'


def _build_pay_string(d):
    s = 'mch={}&money={}&time={}&sign={}&order_id={}&return_url={}&notify_url={}&pay_type={}'.format(
        d['mch'], d['money'], d['time'],
        d['sign'], d['order_id'], d['return_url'],
        d['notify_url'], d['pay_type']
    )
    return s


def _build_query_string(d):
    s = 'order_id={}&mch={}&money={}&pay_type={}&time={}&sign={}'.format(
        d['order_id'], d['mch'], d['money'],
        d['pay_type'], d['time'], d['sign']
    )
    return s


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch', app_id),
        ('pay_type', _get_pay_type(service)),
        ('money', str(int(pay_amount * 100))),
        ('time', str(int(time.time()))),
        ('order_id', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/shenglipay_v2/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/shenglipay_v2/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('extra', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("shenglipay_v2 create: %s", parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    url = _get_gateway(app_id) + '?' + _build_pay_string(parameter_dict)
    _LOGGER.info("shenglipay_v2 create URL : %s", url)
    response = requests.get(url, headers=headers, timeout=3)
    _LOGGER.info("shenglipay_v2 create rsp : %s", response.text)
    resp = json.loads(response.text)
    pay_url = resp.get('data')
    return {'charge_info': pay_url}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("shenglipay_v2 notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('shenglipay_v2 event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['orderNo']
    total_fee = float(data['money']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 1：成功；0：失败
    if trade_status == '1':
        _LOGGER.info('shenglipay_v2 check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch', app_id),
        ('order_id', str(pay_order.id)),
        ('money', str(int(pay_order.total_fee) * 100)),
        ('pay_type', 'aliwap'),
        ('time', str(int(time.time()))),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('shenglipay_v2 query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    url = _get_query_gateway(app_id) + '?' + _build_query_string(parameter_dict)
    response = requests.get(url, headers=headers, timeout=3)
    _LOGGER.info('shenglipay_v2 query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['data'])
        total_fee = float(pay_order.total_fee)
        trade_no = str(json.loads(pay_order.extend).get('trade_no')) if pay_order.extend else ''

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('shenglipay_v2 query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
